import { Vue, Component, Prop } from 'vue-property-decorator';
import commonApi from '@/api/common-api';
import { Dictionary, TableHeaderConfig, DialogObj, PageObj } from '@/typings';
import { transformFields, deepCopy } from '@/utils';
import { Tools } from '@/utils/tools';
import { mergeArray } from '@/utils';
import globalConfig from '@/settings';
import AudioPlayPlugin from '@/utils/audioPlay';
// @ts-ignore
import { multiply, divide } from '@/utils/accuracyLoss';
type AudioType = 'scanBarSuccess' | 'scanBarError' | 'noSame' | 'checkSuccess' | 'scanGoodsSu' | 'scanSendError';

interface SortTableheaderConfig extends TableHeaderConfig {
    index: number;
    id: number;
}
interface ScanDealArgs {
    scanReturnData: Dictionary<any>;
    quantity: number;
    keyword: string;
    enterPriceFlag: boolean;
    fullSizeFlag: boolean;
    scanType: number;
}
interface SomePirceScanArgs {
    scanArr: any[];
    fullSizeFlag: boolean;
}
import BaseScan from '@/components/base-scan/index.vue';
import library from '../library/index';
import GoodsInput from '@/layout-components/goods-input/index.vue';
const audioMap = {
    scanBarSuccess: require('@/assets/audio/checkIn.mp3'),
    scanBarError: require('@/assets/audio/checkOut.mp3'),
    noSame: require('@/assets/audio/CheckSendSu.mp3'),
    checkSuccess: require('@/assets/audio/checkSuccess.mp3'),
    scanGoodsSu: require('@/assets/audio/ScanGoodsSu.mp3'),
    scanSendError: require('@/assets/audio/ScanSendError.mp3')
};
import scanRequest from '@/api/common-api/scan';

const PERMISSION_KEY_MAP = new Map([
    ['balancePrice', 'balance_price'], // 结算价和折扣 金额的权限是绑定的
    ['discount', 'balance_price'],
    ['totalAmount', 'balance_price']
]);
@Component({
    components: {
        BaseScan,
        GoodsInput,
        fileImport: () => import('@/layout-components/import-file/index.vue'),
        productDetailOperation: () => import('@/layout-components/product-detail-operation/index.vue'),
        fieldsSortDialog: () => import('@/layout-components/fields-sort-dialog/index.vue'),
        barcodeRecord: () => import('@/layout-components/barcode-record/index.vue'),
        baseDatePicker: () => import('@/components/base-datePicker/index.vue'),
        baseTable: () => import('@/components/base-table/index.vue'),
        tableImage: () => import('@/views/report-center/report-components/table-img.vue'),
        baseInput: () => import('@/components/base-input/index.vue'),
        baseDialog: () => import('@/components/base-dialog/index.vue'),
        baseSelect: () => import('@/components/base-select/index.vue'),
        basePagination: () => import('@/components/base-pagination/index.vue')
    }
})
export default class ProductDetail extends Vue {
    @Prop({
        default: () => {
            return {};
        }
    })
    rowExDate: object;

    // 默认取消约束
    // cancelCheckParameter: string[] = ['longId']
    cancelCheckParameter: string[] = [];
    // 默认扫描类型
    sweepType: any = 'public';
    // 单据字段 用于映射
    billFiled: string = '';
    m_audioSrc = audioMap['scanBarSuccess'];

    m_customerFieldsMap: Dictionary = {
        goodsFields: [],
        customer: []
    };
    m_tableHeader: TableHeaderConfig[] = [];
    m_sizeDialog: DialogObj = {
        isShowDialog: false,
        title: '',
        width: '50%'
    };
    m_showSizeTable: boolean = false;
    m_skuHeaderObj: Dictionary = {}; // 用于存储尺寸表头的数据
    m_currentSizeTable: TableHeaderConfig[] = []; // 当前尺寸表头的数据
    m_currentSizeData: any[] = [];
    m_goodsSkuData: any[] = []; // sku 尺码数据
    m_goodsSkuTable: TableHeaderConfig[] = []; // sku 尺码表头数据
    m_sizeHeader: any[] = []; // sku 尺码表头数据 只包含 尺码信息
    m_skuDetailName: string = '';
    m_enterPrice: boolean = false;
    tableKey: number = 0;
    focusIndex: number = 0;
    m_detailPage: PageObj = {
        pageSize: 25,
        pageNo: 1,
        total: 0,
        pageCount: 0
    };
    m_audioPlayPlugin: AudioPlayPlugin;
    m_defaultPageSizes: number[] = [25, 50, 100, 200];
    m_goodsInputIndex: number = 0;
    get m_decimal_Places(): number {
        return Number(localStorage.getItem('Quantity_Decimal_Places')) || 2;
    }
    get m_Price_Decimal_Places(): number {
        return Number(localStorage.getItem('Price_Decimal_Places')) || 2;
    }
    mounted() {
        setTimeout(() => {
            this.$nextTick(() => {
                if (!this.$refs.audio) {
                    console.error('请先设置 audio 标签');
                }
                this.m_audioPlayPlugin = new AudioPlayPlugin(this.$refs.audio as HTMLAudioElement);
            });
        }, 20);
    }
    // 获取自定义字段
    async m_getProductDetailTableFields(
        totalColumn: string[],
        typeMap: Map<string, string>,
        column?,
        optionsMap?,
        replaceFieldName?,
        key?: string // 多视图  名称[normal 默认模块视图]
    ) {
        let res: any = null;
        if (column) {
            res = { code: 0, data: column };
        } else {
            res = await this._post({
                url: commonApi.getCustomHeader,
                data: {
                    data: {
                        moduleId: this.$route.meta.moduleId,
                        // 如果key为normal则是默认视图  不需传递给后端  normal只是个标识用于存储到对象
                        key: key ? (key === 'normal' ? undefined : key) : undefined
                    }
                }
            });
        }
        if (res.code === 0) {
            this.m_customerFieldsMap.customer = [];
            this.m_tableHeader = res.data
                .map((item: any) => {
                    // 自定义字段 map
                    const customer = item.customizeColumnOptionDto;
                    if (item.type === 3 && item.fieldName && customer && customer.userFlag) {
                        // this.m_customerFieldsMap.customer.push(item.fieldName)
                        this.m_customerFieldsMap.customer.push({
                            field: item.fieldName,
                            value: customer.defaultValue,
                            loadPreBillFlag: customer.loadPreBillFlag
                        });
                        // this.m_customerFieldsMap.FiledsWithValue[item.fieldName] = customer.defaultValue
                        if (key) {
                            this.$store.commit(`${this.$route.meta.moduleId}/SET_GOODSCUSTOMMAP`, {
                                key,
                                content: this.m_customerFieldsMap
                            });
                        } else {
                            this.$store.commit(`${this.$route.meta.moduleId}/SET_GOODSCUSTOMMAP`, this.m_customerFieldsMap);
                        }
                    }
                    // 后端有的返回null
                    const widthL = item.columnTitle ? item.columnTitle.length * 14 + 10 * 2 : 34;
                    const obj: any = {
                        // 是否启用
                        used: customer ? customer.userFlag : 1,
                        label: item.columnTitle,
                        value: item.fieldName === 'discountName' ? 'discount' : item.fieldName,
                        fieldClass: item.type, // 字段分类 1是固定字段 2是货品模块字段 3是自定义字段
                        type: customer ? customer.typeName : typeMap.get(item.fieldName),
                        index: item.orderNumber,
                        width: item.fieldName === 'deliveryDate' ? '140px' : widthL > 80 ? widthL + 'px' : '80px',
                        id: item.id,
                        isShowTotal: totalColumn.includes(item.fieldName)
                    };
                    if (PERMISSION_KEY_MAP.get(obj.value)) {
                        obj.permissionKey = PERMISSION_KEY_MAP.get(obj.value);
                    }
                    // 如果有自定义字段
                    if (customer && customer.userFlag) {
                        obj.required = customer.requireFlag;
                        // 如果 为下拉框
                        if (customer.options) {
                            obj[`${item.fieldName}_options`] = transformFields(customer.options, {
                                label: 'value',
                                value: 'id'
                            });
                        }
                    }
                    if (replaceFieldName && replaceFieldName[item.fieldName]) {
                        obj['value'] = replaceFieldName[item.fieldName];
                    }
                    // 需要配置下拉
                    if (optionsMap && optionsMap[obj['value']]) {
                        obj[`${obj['value']}_options`] = optionsMap[obj['value']];
                    }
                    return obj;
                })
                .filter((item) => item.value && item.used);
            this.tableKey = this.tableKey + 1;
        }
    }
    // 更新分页数据
    m_updateDetailPage(total: number) {
        const pageCount = Math.ceil(total / globalConfig.pageSize);
        if (!this.m_defaultPageSizes.includes(globalConfig.pageSize)) {
            this.m_defaultPageSizes.unshift(globalConfig.pageSize);
        }
        this.m_detailPage = Object.assign(this.m_detailPage, {
            total,
            pageCount,
            pageSize: globalConfig.pageSize
        });
    }
    // 更新tableData的自定义字段
    m_updateTableData(arr: any[]) {
        arr.forEach((item) => {
            if (item.customFields) {
                for (const k in item.customFields) {
                    item[k] = item.customFields[k];
                }
            }
        });
    }

    // 光标的聚焦点
    //   监听 enter
    nextFocus(event: Event, index: number) {
        event.preventDefault();
        //   因为 原本的 index 是当前处于那列的数值 而表格有多行 所以 这里的 index 需要 行数 * 当前行 input 数量
        return (this.focusIndex = index + 1);
    }
    //   监听 tab
    tabNextFocus(event: Event, index: number) {
        return (this.focusIndex = index);
    }
    //   监听 fouce
    inputChange(index: number) {
        this.focusIndex = index;
    }
    m_deleteItem({ $index }) {
        (this as any).tableData.splice($index, 1);
        this.m_showSizeTable = false;
    }
    // 打开字段排序弹窗
    m_openFieldsSort() {
        (this.$refs.fieldsSort as any).open();
    }
    m_exterPriceChange(val: boolean) {
        this.m_enterPrice = val;
    }
    m_reset() {
        // ;(this as any).m_barcodeRecord.splice(0)
        this.$store.commit(`${this.$route.meta.moduleId}/RESET_BARCODE_RECORD`, []);
        this.m_skuHeaderObj = {};
        this.m_currentSizeData = [];
        this.m_currentSizeTable = [];
        this.m_goodsSkuData = [];
        this.m_goodsSkuTable = [];
        this.m_showSizeTable = false;
    }
    // 格式化图片
    // @ts-ignore
    m_formatImageUrl(GoodsNo) {
        const server = localStorage.getItem('Inner_File_Service_Address');
        if (server && GoodsNo) {
            return `${server}/resource/goodsFile/${GoodsNo}.jpg`;
        } else {
            return library.placeholderGoods;
        }
    }
    // 表格必填字段高亮显示
    m_isRequire(item: Dictionary, row: Dictionary): string | void {
        if (item.required) {
            if (!row[item.value]) {
                return 'red-border';
            }
        }
    }
    // 字段顺序排序
    async m_fieldsSortFn(sortList?: SortTableheaderConfig[]) {
        // const billColumnSettingList = sortList.map((item) => {
        //   return {
        //     orderNumber: item.index,
        //     id: item.id
        //   }
        // })
        // const res = await this._put({
        //   url: commonApi.updatedCustomHeaderSort,
        //   data: {
        //     data: {
        //       billColumnSettingList
        //     }
        //   }
        // })
        // if (res.code === 0) {
        //   this.$message({ message: '排序成功', type: 'success' })
        //   this.m_tableHeader = sortList
        //   this.tableKey += 1
        // }
        // console.error(sortList)
        // this.m_tableHeader = sortList
        // this.tableKey += 1
        console.log(sortList);
        // @ts-ignore
        this.getFields();
    }
    // 延迟
    timeOutDelay: any = null;

    // 输入数量的校验
    m_inputValidate(row: Dictionary, key: string, value: number) {
        if (isNaN(value)) {
            row[key] = 0;
        }
        if (Number(value) < 0) {
            this._message({ message: '不能输入负数', type: 'warning' });
            row[key] = 0;
        }
        // 这里对欠数做判断
        // console.log('row', row);
        // if (value > Number(row.oweQuantity[key])) {
        //     this.$message({ message: '不能大于欠数,自动改成最大数', type: 'warning' });
        //     row[key] = row.oweQuantity[key];
        // }

        row[key] = Number(row[key].toFixed(this.m_decimal_Places));
        this.m_culcalSkuTotal(this.m_goodsSkuData);
    }

    // 更新金额/视图面板
    m_updateTableRow() {
        this.$nextTick(() => {
            try {
                this.$store.dispatch(`${this.$route.meta.moduleId}/v_calculateBillTotalInfo`, (this as any).tableData);
            } catch (e) {
                console.log(e);
            }
        });
    }
    // 处理同款多价格的录入
    m_dealSomePrice({ scanArr, fullSizeFlag }: SomePirceScanArgs) {
        console.log('scanArr', scanArr, 'fullSizeFlag', fullSizeFlag);
        let searchIndex: number = 0;
        scanArr.forEach((item, index) => {
            // const scanObj = scanArr.find((scan) => scan.salePlanGoodsId === item.salePlanGoodsId)
            // if (scanArr.findIndex((scanObj) => scanObj.salePlanGoodsId === item.salePlanGoodsId) === -1) {
            //     this.m_addRowWithTableData({ ...scanObj, ...this.rowExDate }, scanObj.goodsFields);
            // }
            // 如果在列表中没有则插入
            searchIndex = (this as any).tableData.findIndex((goodsItem: any) => goodsItem.salePlanGoodsId === item.salePlanGoodsId);
            if (searchIndex === -1) {
                this.m_addRowWithTableData({ ...item, ...this.rowExDate }, item.goodsFields);
                searchIndex = (this as any).tableData.length - 1;
                this.m_getOnlySkuWithValue(searchIndex, item, item.quantity, fullSizeFlag);
            } else {
                // 有相同则把 sku 进行运算
                this.m_getOnlySkuWithValue(searchIndex, item, item.quantity, fullSizeFlag);
            }
        });
        this.m_playAudio('scanBarSuccess');
        // console.log('searchIndex', searchIndex);
        this.m_scrollRowAndHeightLight(searchIndex);
    }

    // 处理扫码之后的逻辑
    m_dealScanAfterAction(
        { scanReturnData, quantity, keyword, enterPriceFlag, fullSizeFlag, scanType }: ScanDealArgs // scanReturnData: Dictionary, // number: number, // barcode: string, // fullSizeFlag: boolean, // scanType: number
    ) {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { goodsSkuDto, goodsFields } = scanReturnData;
        // rowExDate 是额外的参数
        const productDetail = { ...scanReturnData, ...this.rowExDate };
        const goodsCode = productDetail.goodsCode;
        // 先去列表里面找 如果未找到该条形码对应的 货号 则往列表里面添加一条
        let matchObjIndex = (this as any).tableData.findIndex((item) => item.goodsCode === goodsCode);
        // 如果没有在当前列表中匹配到 则直接创建一条 如果勾选了录入新价格也是同样 同款不同价格
        if (matchObjIndex === -1 || enterPriceFlag) {
            // 往列表里面添加一条数据 这里需要合并 固定字段 货品配置字段 自定义字段
            this.m_addRowWithTableData(productDetail, goodsFields);
            matchObjIndex = (this as any).tableData.length - 1;
        }
        // 扫码提示音
        this.m_playAudio('scanBarSuccess');
        // 根据该条形码 获取到的 颜色 内长 找到对应的 SKU 并且添加数量
        this.m_getOnlySkuWithValue(matchObjIndex, scanReturnData, quantity, fullSizeFlag);

        // 滚动到最底部
        this.m_scrollRowAndHeightLight(matchObjIndex);

        // 往扫码记录里面添加一条数据
        this.m_addBarcodeRecord(productDetail, quantity, keyword, scanType);
        // this.tableKey = this.tableKey + 1
    }
    m_playAudio(audioType: AudioType) {
        this.m_audioSrc = audioMap[audioType];
        this.m_audioPlayPlugin.playAudio();
    }
    m_addRowWithTableData(otherData, goodsFields) {
        const customFields = {};
        this.m_customerFieldsMap.customer.forEach((item) => {
            // customFields[item] = ''
            // if (item.value) {
            customFields[item.field] = item.value;
            // }
        });
        // 这里需要合并 固定字段 货品配置字段 自定义字段
        (this as any).tableData.push(Object.assign({}, otherData, customFields, { goodsFields }, { customFields }));
    }
    m_getOnlySkuWithValue(matchObjIndex: number, scanReturnData: Dictionary, number: number, fullSizeFlag?: boolean, culcalSkuTotal: boolean = true) {
        // const quantity = number > 0 ? number : 0;
        const quantity = number;

        // console.log('scanReturnData', scanReturnData)
        const {
            goodsSkuDto: { dataList },
            ...barcodeScanResp
        } = scanReturnData;
        // 这里要过滤尺码限制
        const size = dataList[0].sizeList.filter((sizeItem) => sizeItem.flag).map((size) => size.fieldName);

        const currentTable = (this as any).tableData[matchObjIndex];
        const addRow: Dictionary = {
            // colorName: `${barcodeScanResp.colorCode}-${barcodeScanResp.colorName}`,
            colorName: barcodeScanResp.colorName,
            colorCode: barcodeScanResp.colorCode,
            longName: barcodeScanResp.longName,
            colorId: barcodeScanResp.colorId,
            longId: barcodeScanResp.longId,
            [barcodeScanResp.fieldName]: quantity
        };
        // 如果有齐码则 该货品颜色内长下的所有尺码都应增加
        if (fullSizeFlag) {
            for (const value of size) {
                addRow[value] = quantity;
            }
        }

        if (currentTable.billSizeList) {
            const result = currentTable.billSizeList.find((em) => {
                return em.colorId === barcodeScanResp.colorId && em.longId === barcodeScanResp.longId;
            });
            if (result) {
                if (fullSizeFlag) {
                    for (const value of size) {
                        // 如果是相同尺码则累加
                        result[value] = (result[value] || 0) + quantity;
                    }
                } else {
                    // 不同尺码则添加尺码
                    result[barcodeScanResp.fieldName] = (result[barcodeScanResp.fieldName] || 0) + quantity;
                }
            } else {
                // 没有则添加
                currentTable.billSizeList.push(addRow);
            }
        } else {
            const billSizeList: any[] = [];
            billSizeList.push(addRow);
            this.$set(currentTable, 'billSizeList', billSizeList);
        }
        // 计算 sku 的合计
        if (culcalSkuTotal) {
            this.m_culcalSkuTotal(currentTable.billSizeList, currentTable);
            this.$store.dispatch(`${this.$route.meta.moduleId}/v_calculateBillTotalInfo`, (this as any).tableData);
        }
    }

    m_addBarcodeRecord(scanInfo: Dictionary, number: number, barcode: string, scanType: number) {
        const item = {
            scanType,
            number,
            scanKeyword: barcode,
            ...scanInfo
        };
        // 添加扫码记录
        // ;(this as any).m_barcodeRecord.push(Tools.barcodeObj(item))
        this.m_audioPlayPlugin.playNumberAudio(number);
        this.$store.commit(`${this.$route.meta.moduleId}/SET_BARCODE_RECORD`, Tools.barcodeObj(item));
    }
    m_productDtailGoodsInput(row: Dictionary) {
        // 根据条码匹配到数据
        this.m_goodsInputIndex = (this as any).tableData.findIndex((item) => item.goodsCode === row.goodsCode);
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { barcodeScanResp, goodsFields, ...otherData } = row;

        // 如果没有在当前列表中匹配到 则直接创建一条 如果勾选了录入新价格也是同样 同款不同价格
        if (this.m_goodsInputIndex === -1 || this.m_enterPrice) {
            // 往列表里面添加一条数据
            this.m_addRowWithTableData(otherData, goodsFields);
            this.m_goodsInputIndex = (this as any).tableData.length - 1;
            // 滚动到最底部且高亮
            this.m_scrollRowAndHeightLight(this.m_goodsInputIndex);
        } else {
            // 如果有在列表中找到数据 滚动到当前行并且高亮
            this.m_scrollRowAndHeightLight(this.m_goodsInputIndex);
        }
    }
    // 详情页的导入
    m_importGoods(importGoods: any[]) {
        (this as any).tableData = mergeArray((this as any).tableData, importGoods, 'goodsCode');
        this.m_updateTableRow();
    }

    // 货品的定位
    m_fixGoodsCodeFn(code: string) {
        const index = (this as any).tableData.findIndex((item) => item.goodsCode === code);
        if (index === -1) {
            this._message({
                message: '找不到该货号,是否输入正确的货号',
                type: 'warning'
            });
            return;
        }
        this.m_scrollRowAndHeightLight(index);
        this.m_viewSkuDetail((this as any).tableData[index]);
    }
    validateTable() {
        // return (this as any).tableData.some((item) => {
        //   return this.m_tableHeader.some((fields): boolean | void => {
        //     if (fields.required) {
        //       if (!item[fields.value]) {
        //         this.$message({ message: `货品明细,${fields.label}未填写`, type: 'warning' })
        //         this.$nextTick(() => {
        //           ;(this.$refs.goodsDetailTable as any).setHighLightRow(item)
        //         })
        //         return true
        //       }
        //     }
        //   })
        // })
        // 优化
        // eslint-disable-next-line no-unreachable
        const table = (this as any).tableData;
        const header = this.m_tableHeader;
        for (let a = 0; a < table.length; a++) {
            const item = table[a];
            for (let b = 0; b < header.length; b++) {
                const fields = header[b];
                if (fields.required) {
                    if (!item[fields.value]) {
                        this.$message({
                            message: `货品明细,${fields.label}未填写`,
                            type: 'warning'
                        });
                        this.$nextTick(() => {
                            (this.$refs.goodsDetailTable as any).setHighLightRow(item);
                        });
                        return true;
                    }
                }
            }
        }
        return false;
    }
    m_scrollRowAndHeightLight(index: number) {
        (this.$refs.goodsDetailTable as any).tableScroll(index * 28);
        (this.$refs.goodsDetailTable as any).setHighLightRow((this as any).tableData[index]);
    }
    // 选择第一个货品
    m_viewFirstDetail() {
        setTimeout(() => {
            (this as any).tableData.length &&
                (() => {
                    try {
                        this.m_viewSkuDetail((this as any).tableData[0]);
                        (this.$refs.goodsDetailTable as any).setHighLightRow((this as any).tableData[0]);
                    } catch (e) {
                        (this.$refs['goodsDetailTable'] as any).viewFirstDetail();
                    }
                })();
        }, 500);
    }
    async m_viewSkuDetail(row: Dictionary) {
        if (!(row.billSizeList && row.billSizeList.length) || row['goodsType'] === 2) {
            this.m_showSizeTable = false;
            return;
        }
        this.m_showSizeTable = true;

        if (this.m_skuHeaderObj[row.goodsId]) {
            this.m_currentSizeTable = this.m_skuHeaderObj[row.goodsId];
        } else {
            Tools.debounce(this.getSkuHeader(row.goodsId), 100);
        }

        row.billSizeList.forEach((item) => {
            if (item.colorName.indexOf(item.colorCode) === -1) {
                item.colorName = `${item.colorCode}-${item.colorName}`;
            }
        });
        this.m_currentSizeData = row.billSizeList;
    }
    async getSkuHeader(goodsId) {
        const res = await this._post({
            url: commonApi.getGoodsSkuHeader,
            data: {
                data: {
                    moduleId: this.$route.meta.moduleId,
                    goodsId
                }
            }
        });
        if (res.code === 0) {
            this.m_currentSizeTable = this.getSizeTableHeader(res.data);
            this.m_skuHeaderObj[goodsId] = this.m_currentSizeTable;
        }
    }
    getSizeTableHeader(arr: any[]) {
        const currentSizeTable = arr.map((item) => {
            if (item.value === 'colorName' || item.value === 'longName') {
                item.width = '110px';
            } else {
                item.width = '60px';
                item.isShowTotal = true;
            }
            return item;
        });
        // 增加合计行
        currentSizeTable.push({
            label: '合计',
            value: 'quantity',
            width: '110px',
            isShowTotal: true
        });
        return currentSizeTable;
    }
    // 弹窗数量录入确定
    m_cancel() {
        if (!(this as any).tableData[this.m_goodsInputIndex].billSizeList) {
            this.$set((this as any).tableData[this.m_goodsInputIndex], 'billSizeList', []);
            this.$nextTick(() => {
                this.m_viewSkuDetail((this as any).tableData[this.m_goodsInputIndex]);
            });
        }
    }
    // 数量录入确定
    m_confirm() {
        this.m_skuInputConfirm();
        this.$nextTick(() => {
            this.m_viewSkuDetail((this as any).tableData[this.m_goodsInputIndex]);
        });
    }
    m_skuInputConfirm() {
        // 往 tableData 里面增加尺码明细数据
        const sizeDetail: any[] = deepCopy(this.m_goodsSkuData);
        // 这里只更新输入了的数据
        const updateSizeDetail = sizeDetail.filter((item) => {
            return this.m_sizeHeader.some((size) => item[size]);
        });
        this.$set((this as any).tableData[this.m_goodsInputIndex], 'billSizeList', updateSizeDetail);

        this.m_updateTableRow();
        // 更新底部汇总
        const ref = this.$refs['goodsDetailTable'] as any;
        ref && ref.updateFooter();
    }
    // 单一物料输入数量改变价格
    m_singleGoodsInput(value, row) {
        this.$set(row, 'quantity', Number(value));

        this.$set(row, 'totalAmount', (Number(value) * row.balancePrice).toFixed(this.m_Price_Decimal_Places));

        this.m_updateTableRow();
    }
    // 结算价格的改变 会改变折扣和金额
    m_balancePriceChange(value, row) {
        row.balancePrice = value;
        // row.discount = divide(Number(value), row.tagPrice, this.m_decimal_Places)
        row.discount = Number(value / row.tagPrice).toFixed(this.m_decimal_Places);

        console.log('row.discount', row.discount);
        this.$set(row, 'totalAmount', (Number(row.quantity) * row.balancePrice).toFixed(this.m_Price_Decimal_Places));

        this.m_updateTableRow();
    }
    // 折扣发生变化 结算价也会变
    m_discountChange(value, row) {
        clearTimeout(this.timeOutDelay);
        // @ts-ignore
        value = this._isFloat(value) ? value : 0;
        this.timeOutDelay = setTimeout(() => {
            row.discount = divide(value, 100, this.m_decimal_Places);
            row.balancePrice = multiply(row.tagPrice, row.discount, this.m_decimal_Places);
            this.$set(row, 'totalAmount', (Number(row.quantity) * row.balancePrice).toFixed(this.m_Price_Decimal_Places));
            this.m_updateTableRow();
            // 现在改成blur事件触发,防抖先改0不删
        }, 0);
    }
    // 计算当前明细的总数 和 每行的尺码总数
    m_culcalSkuTotal(arr: any[], row?: Dictionary) {
        arr.forEach((item) => {
            item.quantity = 0;
            for (const k in item) {
                // if (this.m_sizeHeader.includes(k)) item.quantity = Number(item[k]) + Number(item.quantity)
                if (/^[s]\d+$/.test(k)) {
                    item.quantity = Number(item[k]) + Number(item.quantity);
                }
            }
        });
        if (row) {
            row.quantity = arr.reduce((prev, next) => {
                return prev + next.quantity;
            }, 0);
            row.totalAmount = (row.quantity * row.balancePrice).toFixed(this.m_Price_Decimal_Places);
        }
    }

    // 算当前货品行数量综合 只要当前行数据变化了 就计算 行合计和行总金额
    m_culcalRowTotal(arr: any[], row): number {
        if (!arr || arr.length === 0) return 0;
        const total = arr.reduce((prev, next) => {
            return prev + next.quantity;
        }, 0);
        this.$set(row, 'quantity', total);
        this.$set(row, 'totalAmount', (total * row.balancePrice).toFixed(this.m_Price_Decimal_Places));
        return total;
    }
    m_dealSkuInfo(row: Dictionary, data?: Dictionary<any[]>) {
        // const { dataList, headerList } = data;
        // this.m_sizeHeader = [];
        // this.m_goodsSkuTable = [];
        // if (!dataList) {
        //     this._message({ message: '没有尺码数据', type: 'warning' });
        //     this.m_goodsSkuData = [];
        //     return;
        // }
        // // 得到 sku 的数据
        // this.m_goodsSkuData = this.m_dealSkuData(dataList, row.billSizeList);
        // this.m_skuDetailName = `${row.goodsName}-${row.goodsType === 1 ? '普通物料' : '单一物料'}`;
        // // 得到sku 表头的数据
        // this.m_goodsSkuTable = headerList.map((item) => {
        //     if (item.value === 'colorName' || item.value === 'longName') {
        //         item.fixed = 'left';
        //     }
        //     if (item.value.indexOf('s') === 0) {
        //         item.type = 'number';
        //         item.isShowTotal = true;
        //         item.width = '100px';
        //         this.m_sizeHeader.push(item.value);
        //     }
        //     return item;
        // });
        const { dataList, headerList } = row.goodsSkuDto;
        this.m_sizeHeader = [];
        this.m_goodsSkuTable = [];
        if (!dataList) {
            this._message({ message: '没有尺码数据', type: 'warning' });
            this.m_goodsSkuData = [];
            return;
        }
        // 得到 sku 的数据
        this.m_goodsSkuData = this.m_dealSkuData(dataList, row.billSizeList);
        this.m_skuDetailName = `${row.goodsName}-${row.goodsType === 1 ? '普通物料' : '单一物料'}`;
        // 得到sku 表头的数据
        this.m_goodsSkuTable = headerList.map((item) => {
            if (item.value === 'colorName' || item.value === 'longName') {
                item.fixed = 'left';
                item.width = '120px';
            }
            if (item.value.indexOf('s') === 0) {
                item.type = 'number';
                item.isShowTotal = true;
                item.width = '100px';
                this.m_sizeHeader.push(item.value);
            }
            return item;
        });
        this.m_goodsSkuTable.push({
            label: '合计',
            value: 'quantity',
            fixed: 'right',
            isShowTotal: true
        });
        // 合并小计行
        this.m_culcalSkuTotal(this.m_goodsSkuData, row);
    }
    m_dealSkuData(dataList: any[], billSizeList: any[]) {
        const skuData: any[] = [];
        this.focusIndex = 0;
        dataList.forEach((item, findex) => {
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            const { refreneceList, sizeList, colorName, ...other } = item;
            const obj: Dictionary = Object.assign({}, other, {
                colorName: `${other.colorCode}-${colorName}`,
                oweQuantity: {}
            });
            // 这里只需要在第一条时候去做执行
            if (item.colorId && findex === 0) {
                this.focusIndex += 1;
            }
            if (item.longId && findex === 0) {
                this.focusIndex += 1;
            }
            if (sizeList.length) {
                sizeList.forEach((size, index) => {
                    // 这里是获取到对应尺码的数量
                    if (billSizeList) {
                        const sizeValueObj = billSizeList.find((sizeValue) => sizeValue.colorId === item.colorId && sizeValue.longId === item.longId);
                        if (sizeValueObj) {
                            obj[size.fieldName] = sizeValueObj[size.fieldName] || '';
                        }
                    }

                    obj.inputLength = index + 1;
                    obj.oweQuantity[size.fieldName] = size.oweQuantity;
                });
            }
            skuData.push(obj);
        });
        return skuData;
    }
    // 获取货品明细分页的数据
    async m_getGoodsPageList(url: string) {
        const v_id = this.$store.state[this.$route.meta.moduleId].v_id;
        const id = v_id.split('_')[0] || '';
        if (!id) return;
        const res = await this._post({
            url,
            data: {
                data: {
                    billId: id
                },
                page: this.m_detailPage.pageNo,
                pageSize: this.m_detailPage.pageSize
            }
        });
        if (res.code === 0) {
            const { pageCount, pageSize, total, data } = res;
            this.m_detailPage = Object.assign(this.m_detailPage, {
                pageCount,
                pageSize,
                total
            });
            (this as any).tableData = data;
            this.m_showSizeTable = false;
        }
    }
    // 在浏览的状态下获取货品所在的页数
    async m_getGoodsCodeInPage(code: string, pageUrl: string, skuHeaderUrl?: string, tableNo: string = '01') {
        const index = (this as any).tableData.findIndex((item) => item.goodsCode === code);
        // 如果在当前列表有找到则不需要通过接口获取
        if (index !== -1) {
            this.m_scrollRowAndHeightLight(index);
            this.m_viewSkuDetail((this as any).tableData[index]);
            return;
        }
        const v_id = this.$store.state[this.$route.meta.moduleId].v_id;
        const id = v_id.split('_')[0] || '';
        const res = await this._post({
            url: commonApi.goodsFixed,
            data: {
                billId: id,
                goodsCode: code,
                pageSize: this.m_detailPage.pageSize,
                tableNo: `${this.$route.meta.baseModuleId}${tableNo}`
            }
        });
        if (res.code === 0) {
            if (res.data === -1) {
                this._message({
                    message: '输入的货号不存在当前单据内',
                    type: 'warning'
                });
                return;
            }
            this.m_detailPage['pageNo'] = res.data;
            await this.m_getGoodsPageList(pageUrl);
            this.m_fixGoodsCodeFn(code);
        }
    }
    readSizeArray(row) {
        return Object.keys(row).filter((em) => {
            return em.match(/^s\d+/) && row[em];
        });
    }
    // 删除指定约束条件
    deleteCheckParameter(array: string[]) {
        const copyPaste = JSON.parse(JSON.stringify(array));
        if (this.cancelCheckParameter.length) {
            this.cancelCheckParameter.forEach((em) => {
                copyPaste.splice(copyPaste.indexOf(em), 1);
            });
        }
        return copyPaste;
    }
    // 扫条码
    async m_skuBarcode_({ keyword, quantity, fullSizeFlag, enterPriceFlag, scanType, ...other }, resetEcterPriceFlagFn: Function) {
        try {
            const requestData = scanRequest.requestCheck(
                this.deleteCheckParameter(scanRequest.parameterConstraint[this.sweepType].barCode),
                {
                    keyWord: keyword,
                    quantity,
                    moduleId: this.$route.meta.moduleId,
                    ...other,
                    billIdList: this.billFiled ? (other[this.billFiled] ? [other[this.billFiled]] : undefined) : undefined
                },
                this.sweepType
            );
            if (requestData) {
                const res = await this._post({
                    url: `${scanRequest.requestInterface(this.sweepType, 'barCode')}`,
                    data: {
                        data: Object.assign({}, requestData, { scanNewPriceFlag: enterPriceFlag })
                    }
                });
                if (res.code === 0) {
                    const scanResponseData: Dictionary<any> = res.data;
                    // 如果返回结构有  mulPriceFlag 则表示该模块支持同款多价
                    if (Object.prototype.hasOwnProperty.call(scanResponseData, 'mulPriceFlag')) {
                        if (scanResponseData.mulPriceFlag) {
                            const scanGoodsId = scanResponseData.billScanBarcodeRespList[0].goodsId;
                            // 根据 goodsId 判断是否有录入
                            const hasInputArr = (this as any).tableData.filter((goodsItem) => goodsItem.goodsId === scanGoodsId);
                            const somePriceResponse: Dictionary = await this._post({
                                url: `${scanRequest.requestInterface(this.sweepType, 'barCode')}`,
                                data: {
                                    data: Object.assign(requestData, {
                                        scanNewPriceFlag: enterPriceFlag,
                                        billGoodsList: hasInputArr,
                                        mulPriceFlag: true
                                    })
                                }
                            });
                            if (somePriceResponse.code === 0) {
                                this.m_dealSomePrice({ scanArr: somePriceResponse.data.billScanBarcodeRespList, fullSizeFlag: fullSizeFlag });
                            }
                        } else {
                            await this.m_dealScanAfterAction({
                                scanReturnData: scanResponseData.billScanBarcodeRespList[0],
                                quantity: quantity,
                                keyword: keyword,
                                fullSizeFlag: fullSizeFlag,
                                enterPriceFlag: enterPriceFlag,
                                scanType
                            });
                        }
                        // 在这里要加入 同款多价 的逻辑
                    } else {
                        await this.m_dealScanAfterAction({
                            scanReturnData: scanResponseData,
                            quantity: quantity,
                            keyword: keyword,
                            fullSizeFlag: fullSizeFlag,
                            enterPriceFlag: enterPriceFlag,
                            scanType
                        });
                    }

                    resetEcterPriceFlagFn();
                }
                // if (res.code === 0) {
                //     await this.m_dealScanAfterAction({
                //         scanReturnData: res.data,
                //         quantity,
                //         keyword,
                //         fullSizeFlag,
                //         enterPriceFlag,
                //         scanType
                //     });
                //     resetEcterPriceFlagFn();
                // }
            }
        } catch (e) {
            console.log(e);
        }
    }

    // 扫描sku
    // 这里增加一个同款多价格的逻辑 如下
    /**
     * 1. 如果没引用上级单据 则不需要考虑同款多价
     * 2. 如果有用到上级单据 在货品录入的时候先把参数传给服务端查询一遍
     *    2.1 如返回 mulPriceFlag 为 true 则表示有同款多价格 此时在 判断列表中根据 goodsId 是否有录入
     *      2.1.1 如有录入 则需要传入当前行数据给服务端 再次 查询 返回多条数据  该数据和原数据的 sku 进行运算
     *      2.1.2 如没有录入 则把服务端返回的数据 添加至列表
     *
     */
    // m_shuChooseRequestFn() {

    // }
    async m_skuChoose_({ scanType, ...args }, resetEcterPriceFlagFn) {
        console.log('m_skuChoose_ args', args);
        try {
            const requestData = scanRequest.requestCheck(
                this.deleteCheckParameter(scanRequest.parameterConstraint[this.sweepType].sku),
                {
                    ...args,
                    moduleId: this.$route.meta.moduleId,
                    billIdList: this.billFiled ? (args[this.billFiled] ? [args[this.billFiled]] : undefined) : undefined
                },
                this.sweepType
            );

            if (requestData) {
                const res = await this._post({
                    url: `${scanRequest.requestInterface(this.sweepType, 'sku')}`,
                    data: {
                        data: Object.assign({}, requestData, { scanNewPriceFlag: args.enterPriceFlag })
                    }
                });
                if (res.code === 0) {
                    const scanResponseData: Dictionary<any> = res.data;
                    // 如果返回结构有  mulPriceFlag 则表示该模块支持同款多价
                    if (Object.prototype.hasOwnProperty.call(scanResponseData, 'mulPriceFlag')) {
                        if (scanResponseData.mulPriceFlag) {
                            // 根据 goodsId 判断是否有录入
                            const hasInputArr = (this as any).tableData.filter((goodsItem) => goodsItem.goodsId === args.goodsId);
                            const somePriceResponse: Dictionary = await this._post({
                                url: `${scanRequest.requestInterface(this.sweepType, 'sku')}`,
                                data: {
                                    data: Object.assign(requestData, {
                                        scanNewPriceFlag: args.enterPriceFlag,
                                        billGoodsList: hasInputArr,
                                        mulPriceFlag: true
                                    })
                                }
                            });
                            if (somePriceResponse.code === 0) {
                                this.m_dealSomePrice({ scanArr: somePriceResponse.data.billScanBarcodeRespList, fullSizeFlag: args.fullSizeFlag });
                            }
                        } else {
                            await this.m_dealScanAfterAction({
                                scanReturnData: scanResponseData.billScanBarcodeRespList[0],
                                quantity: args.quantity,
                                keyword: args.keyword,
                                fullSizeFlag: args.fullSizeFlag,
                                enterPriceFlag: args.enterPriceFlag,
                                scanType
                            });
                        }
                        // 在这里要加入 同款多价 的逻辑
                    } else {
                        await this.m_dealScanAfterAction({
                            scanReturnData: scanResponseData,
                            quantity: args.quantity,
                            keyword: args.keyword,
                            fullSizeFlag: args.fullSizeFlag,
                            enterPriceFlag: args.enterPriceFlag,
                            scanType
                        });
                    }

                    resetEcterPriceFlagFn();
                }
            }
        } catch (e) {
            console.log(e);
        }
    }
}
